<template>
	<view class="wrap">
		<js-error mode="bottom" ref="jsError" @update:errorcClose="onErrorClose"></js-error>
		<view class="cu-bar search" style="padding: 10px" ref="cu-bar">
			<u-search v-model="barCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描机台" :show-action="false"
				@search="confirmSearch" height="74"></u-search>
			<view style="margin-left: 10px; display: flex; flex-direction: column">
				<u-icon @click="search" name="scan" size="60"></u-icon>
			</view>
		</view>
		<view class="cu-bar search" style="padding: 10px" ref="cuBar" v-if="lineCode">
			<u-form style="width: 100%;">
				<u-form-item label="机台" prop="id" label-width="180" style="font-weight: 800;">
					<view>{{ lineCode}} </view>
				</u-form-item>
			</u-form>
		</view>
		<view v-show="currentRW">
			<scroll-view
			  scroll-y="true"
			  :style="{ height: computedScrollViewHeight }"
			>
			<!-- style="margin: 20px 0" -->
				<view class="margin-sm" >
					<u-section
					  title="投料登记"  
					  :right="false"
					  line-color="blue"
					  font-size="30"
					></u-section>
					<view class="wrap">
						<u-form class="form" ref="uForm" label-position="left" :model="model" :rules="rules">
							<u-form-item label="投料数量" prop="iqty" label-width="180" style="color: red;font-weight: 800;" :required="true" v-if="this.list.length > 0 ">
								<u-input placeholder="请输入" v-model="model.iqty" type="number" maxlength="64" :custom-style="customStyle"></u-input>(KG)
							</u-form-item>
							<view  v-for="(item,index) in list" :key="item.id">
								
								<u-form-item label="" prop="id" label-width="180" style="font-weight: 800;" >
									<template>
										<view class="flex title">
											<view style=" display: inline-block;background: #3E97B0;color: #fff;width: 30px;text-align: center;font-style: italic;font-weight: bold;margin-right: 5px	;">
											{{ index + 1 }}
											</view>
											<view>订单号</view>
										</view>
										<view class="flex align-center justify-between flex-sub">
											<view>{{ item['scOrder'] ? item['scOrder']['code']: '' }} {{ item['scOrder'] ? item['scOrder']['sortNum']? '#' + item['scOrder']['sortNum'] : '' : '' }}</view>
											<!-- <text class="cuIcon-deletefill padding text-sl text-red" @tap="DelItem(item)" v-if="!!item.isDelFlag"></text> -->
										</view>
									</template>
								</u-form-item>
								<u-form-item label="存货编码" prop="id" label-width="180">
									<view>{{ item['basInv']['cinvcode'] ? item['basInv']['cinvcode'] : '' }}</view>
								</u-form-item>
								<u-form-item label="存货名称" prop="id" label-width="180">
									<view>{{ item['basInv']['cinvname'] ? item['basInv']['cinvname'] : '' }}</view>
								</u-form-item>
								<u-form-item label="规格型号" prop="id" label-width="180">
									<view>{{ item['basInv']['cinvstd']? item['basInv']['cinvstd'] : '' }}</view>
								</u-form-item>
								<u-form-item label="计划数" prop="id" label-width="180">
									<view>{{ item['scOrder']? item['scOrder']['iqty'] : '' }}</view>
								</u-form-item>
								
							</view>
						</u-form>
					</view>
					
				</view>
			</scroll-view>
			<view class="btn-group cu-bar foot padding" ref="btn-group">
				<!-- round -->
				<button class="cu-btn  bg-confirm lg margin-left " @click="confirm" v-if="this.list.length > 0 ">确定</button>	
				<button class="cu-btn  lines-red lg " @click="selectSJ">选择投料任务</button>
			</view>
		</view>
		<u-empty v-if="!currentRW" :style="{height: emptyViewHeight+'px'}"></u-empty>	
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				focus:true,
				barCode:'',
				model: {
					iqty:'',
				},
				rules: {
					iqty: [
						{
							required: true,
							message: '请输入投料数量',
							trigger: ['change','blur'],
						}
					],
				},
				customStyle:{
					color:'red'
				},
				scrollViewHeight: 0,
				currentRW:false,
				emptyViewHeight:0,
				lineCode:'',
				list:[],
				showFlag:false,
				
			}
		},
		onLoad() {
			this.$nextTick(() => {
				this.calculateScrollViewHeight()
				this.emptyHeight()
			})
		},
		onShow() {
			// 在onShow中监听事件
			uni.$once('selectedItems', (selectedItems) => {
				if (!Array.isArray(selectedItems)) {
					console.error('selectedItems is not an array');
					return;
				}
				this.focus = false
				setTimeout(() => {
					this.focus = true
				}, 500)
				// 去重
				const uniqueSelectedItems = Array.from(new Set(selectedItems.map(item => item.id)));
				// // 从this.list中过滤出不在uniqueSelectedItems中的项
				// const filteredList = this.list.filter(item => !uniqueSelectedItems.includes(item.id));
				// // 合并并去重
				// this.list = [...filteredList, ...selectedItems].filter(
				// 	(item, index, self) => self.findIndex(i => i.id === item.id) === index
				// );
				// 直接替换list
				this.list = selectedItems;
				console.log(this.list, 'merged and deduplicated list');
			});
		},
		computed: {
		  computedScrollViewHeight() {
		    return this.scrollViewHeight === 'auto' ? 'auto' : `${this.scrollViewHeight}px`;
		  },
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods:{
			async calculateScrollViewHeight() {
			  try {
			// 等待头部高度计算完成
			      
			      // 计算btn-group 高度
			      // 获取屏幕高度
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const btnOffsetHeight = this.$refs['btn-group'] ? this.$refs['btn-group'].$el ? this.$refs['btn-group'].$el.offsetHeight : 0 : 0;
				  const cuBarOffsetHeight = this.$refs['cu-bar'] ? this.$refs['cu-bar'].$el ? this.$refs['cu-bar'].$el.offsetHeight : 109 : 0;
				  console.log(screenHeight,btnOffsetHeight,cuBarOffsetHeight,'===')
			      // 计算scroll-view高度
			      this.scrollViewHeight = screenHeight - ( btnOffsetHeight + cuBarOffsetHeight + 60 );
			  } catch (error) {
			    console.error('Error while calculating ScrollView height:', error);
			  }
			},
			async emptyHeight() {
			  try {
			// 等待头部高度计算完成
			      
			      // 计算btn-group 高度
			      // 获取屏幕高度
			      const systemInfo = uni.getSystemInfoSync();
			      const screenHeight = systemInfo.windowHeight;
				  const cuBarOffsetHeight = this.$refs['cu-bar'] ? this.$refs['cu-bar'].$el ? this.$refs['cu-bar'].$el.offsetHeight : 109 : 0;
			      // 计算scroll-view高度
			      this.emptyViewHeight = screenHeight - cuBarOffsetHeight;
			  } catch (error) {
			    console.error('Error while calculating ScrollView height:', error);
			  }
			},
			confirmSearch(){
				this.focus = false
				this.commonSearch(this.barCode)
			},
			search(){
				var _that = this;
				_that.focus = false
				uni.scanCode({
					scanType: ["barCode", "qrCode"],
					// onlyFromCamera: true,
					success: async (res) => {
						_that.barCode = res.result;
						await _that.commonSearch(res.result)
					},
				});
			},
			confirm(){
				// 去list的id，逗号分隔
				var taskIds = this.list.map(item => item.id).join(',');
				this.$refs.uForm.validate(valid => {
					if (valid) {
						this.$u.api.kst.matLog({
							iqty:this.model.iqty,
							lineCode:this.lineCode,
							modid:this.list[0]['scOrder']['erpModid'],
						}).then((res)=>{
							console.log(res,'res===')
							if (res.result == "true") {
								this.$u.toast('投料登记成功');
								// this.model.iqty = '';
								this.currentRW = false
								this.lineCode = ''
								this.focus = false;
								setTimeout(() => {
									this.focus = true;
								}, 1000);
							}else{
								// this.$u.toast(res.message);
								this.$refs.jsError.showError('',res.message,'error');
							}
						})
					} else {
						this.$u.toast('您填写的信息有误，请根据提示修正。');
					}
				});
			},
			async commonSearch(barCode){				
				let JT = this.vuex_config.JT;
				let GP = this.vuex_config.GP;
				console.log(this.barCode.indexOf(JT),'JT',this.barCode,JT,this.barCode.indexOf(GP))
				if (barCode.indexOf(JT) == -1) {
					this.$refs.jsError.showError('',"请扫描正确的机台",'error');
					return;
				}else if(barCode.indexOf(JT) == 0){

					const res = await this.$u.api.kst.checkFunAndBar({
						funcType:this.vuex_config.JT,
						barJT:barCode
					})
					if (res.result == "true") {
						await this.$nextTick();
						this.barCode = '';
						this.lineCode = res.basLine.code;
						this.currentRW = true;
						// const resResult = await this.$u.api.kst.getTaskByLineCode({
						// 	lineCode:this.lineCode
						// })
						// if (resResult.result == "true") {
							
						// 	this.list = resResult.data
						// 	this.currentRW = true;
						// 	this.modid = this.list.length > 0 ? this.list[0]['modid'] : ''
						// 	this.showFlag = this.list.length > 0  ? true : false
							
						// }else{
						// 	setTimeout(() => {
						// 		this.focus = true;
						// 	}, 500);
						// 	this.$refs.jsError.showError('',resResult.message,'error');
						// }	
						setTimeout(() => {
							this.focus = true;
						}, 500);

					}else{
						setTimeout(() => {
							this.focus = true;
						}, 500);
						this.$refs.jsError.showError('',res.message,'error');
						
					}
				} 
				
			},
			onErrorClose(result) {
				this.focus = result;
				setTimeout(() => {
					this.barCode = ''
					this.focus = true;
				}, 100);
				if(!!result){
					this.currentRW = true;
					this.showFlag = false;
				}
			 
			},
			selectSJ(){
				uni.navigateTo({
					url: "/pages/mes/touliao/bSelect?modid=" + this.modid + '&lineCode=' + this.lineCode
				});
			},
		}
	}	
</script>

<style scoped lang="scss">
	.title{
		width: 220rpx;
	}
	.bg-confirm {
	  background: #3e97b0;
	  color: #ffffff;
	}
	.cu-bar.foot{
		z-index: 998 !important;
	}
</style>